﻿

using System;

public class Solution8
{
    public int MyAtoi1(string s)
    {

        int len = s.Length;
        bool isPositive = true;

        int i = 0;
        int pre = 0;

        while (i < len)
        {


            char c = s[i];
            Console.WriteLine("当前字符：  "+c);
            int cur = c - '0';
            i++;
            if (c == ' ')//丢弃空格
            {



            }
            else if (c == '-')
            {

                isPositive = false;
                Console.WriteLine("失败原因：  " + '-');

            }
            else if (c == '0')//丢弃0，这样会把中间的0跳过去
            {
                Console.WriteLine("失败原因：  " + '0');

            }
            else if (cur < 0 || cur > 9)
            {
                Console.WriteLine("失败原因：  " + "非数字");
                break;
            }
            else
            {

                pre = pre * 10 + cur;
                Console.WriteLine(pre);
            }



        }
      
        if (isPositive)
        {
            return pre;
        }
        else
        {
            return -pre;
        }


    }
    public int MyAtoi(string s)
    {
       
        int len = s.Length;
        if (len == 0)
        {
            return 0;
        }
        bool isPositive = true;

        int i = 0;
        int pre = 0;

        while (i < len && s[i] == ' ')
        {
            i++;  
        }
        Console.WriteLine(i);
        Console.WriteLine(len);

        if (i < len)
        {
            Console.WriteLine("xiao");
        }
        if (i < len && (s[i] == '-' || s[i] == '+'))
        {   if(s[i] == '-')
            {
                isPositive = false;
            }
            i ++;

        }
        while (i < len && char.IsDigit(s[i]))
        {


            int cur = s[i] - '0';
            if (pre > (int.MaxValue - cur) / 10)//越界
            {
                if(isPositive)
                {
                    return int.MaxValue;
                }
                else
                {
                    return int.MinValue;
                }


            }


            pre = pre * 10 + cur;
            i++;
            



        }

        if (isPositive)
        {
            return pre;
        }
        else
        {
            return -pre;
        }


    }
}

class Program8
{

    static void Main8(string[] args)
    {

        string s = " ";
        Solution8 solution = new Solution8();
        int res = solution.MyAtoi(s);
        Console.WriteLine(res);


    }
}